package com.hunt.service.app.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hunt.model.app.CrawlingResult;
import com.hunt.model.app.PopularityResults;
import com.hunt.model.app.PopularityStock;
import com.hunt.service.app.CrawlingPopularityStockService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class CrawlingPopularityStockServiceImpl implements CrawlingPopularityStockService {

    private static final Logger log = LoggerFactory.getLogger(CrawlingPopularityStockServiceImpl.class);

    private static final String url = "https://basic.10jqka.com.cn/api/stockph/popularity/top/";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public void crawlingAndInsert() {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String s = EntityUtils.toString(responseEntity);
                CrawlingResult result = JSON.parseObject(s, CrawlingResult.class);
                saveOrUpdate(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 新增或者修改
     * @param result
     */
    private void saveOrUpdate(CrawlingResult result){
        PopularityResults data = result.getData();
        List<PopularityStock> list = data.getList();
        if (null != list && list.size()>0){
            //如果有key就按角标set
            if (redisTemplate.hasKey("POPULARITY_STOCK_LIST")){
                Jedis jedis = jedisPool.getResource();
                for (PopularityStock popularityStock : list) {
                    try {
                        String index = popularityStock.getHot_rank();
                        PopularityStock pkg = packPopularityStock(jedis, popularityStock);
                        redisTemplate.boundListOps("POPULARITY_STOCK_LIST").set(Integer.parseInt(index)-1,pkg);
                    }catch (Exception e){
                        log.info("存储热点股票失败 :{},原因:{}",popularityStock,e.getMessage());
                        e.printStackTrace();
                    }
                }
                jedis.close();
            //如果没有key就右侧压入
            }else{
                Jedis jedis = jedisPool.getResource();
                for (PopularityStock popularityStock : list) {
                    try {
                        PopularityStock pkg = packPopularityStock(jedis, popularityStock);
                        redisTemplate.boundListOps("POPULARITY_STOCK_LIST").rightPush(pkg);
                    }catch (Exception e){
                        log.info("存储热点股票失败 :{}",popularityStock);
                        e.printStackTrace();
                    }
                }
                jedis.close();
            }
            log.info("爬取同花顺热门股票存储完毕");
        }
    }

    /**
     * 组装数据 (code添加.sz/.sh后缀,添加自己服务的涨跌幅,添加申万行业)
     * @param jedis
     * @param popularityStock
     * @return
     * @throws IOException
     */
    private PopularityStock packPopularityStock(Jedis jedis, PopularityStock popularityStock) throws IOException {
        //添加code后缀
        String code = popularityStock.getCode();
        if (code.startsWith("0") || code.startsWith("3")){
            code += ".sz";
        }else if (code.startsWith("6")){
            code += ".sh";
        }
        popularityStock.setCode(code);
        //添加自己服务的涨跌幅
        List<String> stockData = jedis.hmget("Real_time_Stock_Data", code);
        if (null != stockData.get(0)){
            JSONObject jsonObject = JSON.parseObject(stockData.get(0));
            String hlPercent = jsonObject.getString("hlPercent");
            popularityStock.setHlPercent(hlPercent);
        }
        //添加所属申万行业
        List<String> stock_base_message = jedis.hmget("Stock_Base_Message", code);
        if (null != stock_base_message.get(0)){
            JSONObject jsonObject = JSONObject.parseObject(stock_base_message.get(0));
            String industry = jsonObject.getString("industry");
            popularityStock.setIndustry(industry);
        }
        return popularityStock;
    }
}
